local extension = Package("joy_xd2")
extension.extensionName = "joy"

Fk:loadTranslationTable{
  ["joy_xd2"] = "欢乐-限定2",
}

local U = require "packages/utility/utility"

local mayunlu = General(extension, "joy__mayunlu", "shu", 4, 4, General.Female)
local fengpo = fk.CreateTriggerSkill{
  name = "joy__fengpo",
  anim_type = "offensive",
  events ={fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and (data.card.trueName == "slash" or data.card.trueName == "duel") then
      local room = player.room
      local to = room:getPlayerById(data.to)
      if not to.dead and U.isOnlyTarget(to, data, event) then
        local use_event = room.logic:getCurrentEvent():findParent(GameEvent.UseCard, true)
        if use_event == nil then return false end
        local x = player:getMark("fengpo_record_" .. data.card.trueName.."-turn")
        if x == 0 then
          room.logic:getEventsOfScope(GameEvent.UseCard, 1, function (e)
            local use = e.data[1]
            if use.from == player.id and use.card.trueName == data.card.trueName then
              x = e.id
              room:setPlayerMark(player, "fengpo_record_" .. data.card.trueName.."-turn", x)
              return true
            end
          end, Player.HistoryTurn)
        end
        return x == use_event.id
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askForChoice(player, {"joy__fengpo_draw", "joy__fengpo_damage", "Cancel"}, self.name,
      "#fengpo-choice::"..data.to..":"..data.card:toLogString())
    if choice == "Cancel" then return false end
    room:doIndicate(player.id, {data.to})
    self.cost_data = choice
    return true
  end,
  on_use = function(self, event, target, player, data)
    local to = player.room:getPlayerById(data.to)
    local n = 0
    for _, id in ipairs(to:getCardIds("h")) do
      if Fk:getCardById(id).color == Card.Red then
        n = n + 1
      end
    end
    n = math.min(4,n)
    if self.cost_data == "joy__fengpo_draw" then
      if n > 0 then
        player:drawCards(n, self.name)
      end
    else
      if n > 0 then
        data.additionalDamage = (data.additionalDamage or 0) + n
      end
    end
  end,
}
mayunlu:addSkill("mashu")
mayunlu:addSkill(fengpo)
Fk:loadTranslationTable{
  ["joy__mayunlu"] = "马云騄",
  ["#joy__mayunlu"] = "剑胆琴心",
  ["joy__fengpo"] = "凤魄",
  [":joy__fengpo"] = "当你每回合首次使用【杀】或【决斗】指定目标后，你可以选择一项：1.摸X张牌；2.此牌伤害+X"..
  "（X为其<font color='red'>红色</font>手牌数）且至多为4。",
  ["joy__fengpo_draw"] = "摸X张牌",
  ["joy__fengpo_damage"] = "伤害+X",

}

local lvkai = General(extension, "joy__lvkai", "shu", 3)
local tunan = fk.CreateActiveSkill{
  name = "joy__tunan",
  anim_type = "support",
  card_num = 0,
  min_target_num = 1,
  max_target_num = 2,
  prompt = "#joy__tunan",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected < 2 
  end,
  on_use = function(self, room, effect)
    for _, pid in ipairs(effect.tos) do
        local target = room:getPlayerById(pid)
        local cards = room:getNCards(1)
        local card = Fk:getCardById(cards[1])
        local choices = {}  --选项一无距离限制，选项二有距离限制，不能用interaction……
        if U.getDefaultTargets(target, card, false, true) then
            table.insert(choices, "tunan1:::"..card:toLogString())
        end
        local slash = Fk:cloneCard("slash")
        slash.skillName = self.name
        slash:addSubcard(card)
        if U.getDefaultTargets(target, slash, true, false) then
        table.insert(choices, "tunan2:::"..card:toLogString())
        end
        if #choices == 0 then
        table.insert(room.draw_pile, 1, cards[1])
        return
        end
        local choice = room:askForChoice(target, choices, self.name, nil, nil,
        {"tunan1:::"..card:toLogString(), "tunan2:::"..card:toLogString()})
        local success, dat
        if choice[6] == "1" then
        U.askForUseRealCard(room, target, cards, ".", self.name, nil, {expand_pile = cards, bypass_distances = true}, false, false)
        else
        U.askForUseVirtualCard(room, target, "slash", cards, self.name, "#tunan2-use:::"..card:toLogString(), false, true, false, true)
        end
    end
  end,
}
lvkai:addSkill(tunan)
lvkai:addSkill("bijing")
Fk:loadTranslationTable{
  ["joy__lvkai"] = "吕凯",
  ["#joy__lvkai"] = "铁心司南",
  ["joy__tunan"] = "图南",
  [":joy__tunan"] = "出牌阶段限一次，你可令最名两其他角色依次观看牌堆顶一张牌，然后该角色选择一项：1.使用此牌（无距离限制）；2.将此牌当【杀】使用。",
  ["#joy__tunan"] = "图南：令至多名角色观看牌堆顶牌，其可以使用此牌或将此牌当【杀】使用",

}

local wuxian = General(extension, "joy__wuxian", "shu", 3, 3, General.Female)
local fumian = fk.CreateTriggerSkill{
  name = "joy__fumian",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start
  end,
  on_trigger = function(self, event, target, player, data)
    local room = player.room
    if player:getMark("joy__fumian1_record") > 0 or player:getMark("joy__fumian2_record") > 0 then
      for i = 1, 2, 1 do
        if player:getMark("joy__fumian"..i.."_record") > 0 then
          room:setPlayerMark(player, "joy__fumian"..i.."_record", 0)
          room:setPlayerMark(player, "joy__fumian"..i.."-tmp", 1)
        end
      end
    end
    self:doCost(event, target, player, data)
    room:setPlayerMark(player, "joy__fumian1-tmp", 0)
    room:setPlayerMark(player, "joy__fumian2-tmp", 0)
  end,
  on_cost = function(self, event, target, player, data)
    local choices = {"joy__fumian1:::"..(player:getMark("joy__fumian2-tmp") + 1), "joy__fumian2:::"..(player:getMark("joy__fumian1-tmp") + 1), "Cancel"}
    local choice = player.room:askForChoice(player, choices, self.name)
    if choice ~= "Cancel" then
      self.cost_data = choice
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = self.cost_data[7]
    if n == "1" then
      room:setPlayerMark(player, "@joy__fumian1-turn", player:getMark("joy__fumian2-tmp") + 1)
    else
      room:setPlayerMark(player, "@joy__fumian2-turn", player:getMark("joy__fumian1-tmp") + 1)
    end
    room:setPlayerMark(player, "joy__fumian"..n.."_record", 1)
  end,
}
local fumian_trigger = fk.CreateTriggerSkill{
  name = "#joy__fumian_trigger",
  mute = true,
  events = {fk.DrawNCards, fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    if target == player then
      if event == fk.DrawNCards then
        return player:getMark("@joy__fumian1-turn") > 0
      else
        return player:getMark("@joy__fumian2-turn") > 0 and data.card.color == Card.Red and data.tos and
          #player.room:getUseExtraTargets( data, false) > 0
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.DrawNCards then
      return true
    else
      local tos = player.room:askForChoosePlayers(player, player.room:getUseExtraTargets( data, false), 1, player:getMark("@joy__fumian2-turn"),
        "#fumian-choose:::"..data.card:toLogString()..":"..player:getMark("@joy__fumian2-turn"), "joy__fumian", true)
      if #tos > 0 then
        self.cost_data = tos
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DrawNCards then
      data.n = data.n + player:getMark("@joy__fumian1-turn")
      room:setPlayerMark(player, "@joy__fumian1-turn", 0)
    else
      for _, id in ipairs(self.cost_data) do
        TargetGroup:pushTargets(data.tos, id)
      end
    end
  end,
}
local daiyan = fk.CreateTriggerSkill{
  name = "joy__daiyan",
  anim_type = "support",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
  end,
  on_trigger = function(self, event, target, player, data)
    local room = player.room
    if player:getMark("joy__daiyan_record") ~= 0 then
      local to = room:getPlayerById(player:getMark("joy__daiyan_record"))
      room:setPlayerMark(player, "joy__daiyan_record", 0)
      if not to.dead then
        room:setPlayerMark(to, "@@joy__daiyan-tmp", 1)
      end
    end
    self:doCost(event, target, player, data)
    for _, p in ipairs(room.players) do
      room:setPlayerMark(p, "@@joy__daiyan-tmp", 0)
    end
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, table.map(player.room.alive_players, Util.IdMapper),
      1, 1, "#joy__daiyan-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "joy__daiyan_record", self.cost_data)
    local to = room:getPlayerById(self.cost_data)
    local card = room:getCardsFromPileByRule(".|.|heart|.|.|basic")
    if #card > 0 then
      room:moveCards({
        ids = card,
        to = to.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonJustMove,
        proposer = player.id,
        skillName = self.name,
        moveVisible = true,
      })
    end
    if not player.dead and to:getMark("@@joy__daiyan-tmp") == 0 then
      player:drawCards(1,self.name)
    end
  end,
}
fumian:addRelatedSkill(fumian_trigger)
wuxian:addSkill(fumian)
wuxian:addSkill(daiyan)
Fk:loadTranslationTable{
  ["joy__wuxian"] = "吴苋",
  ["#joy__wuxian"] = "穆皇后",

  ["joy__fumian"] = "福绵",
  [":joy__fumian"] = "准备阶段，你可以选择一项：1.本回合下个摸牌阶段摸牌数+1；2.本回合你使用红色牌时，可以令此牌目标数+1。若你选择的选项"..
  "与你上回合选择的选项不同，则本回合该选项数值+1。",
  ["joy__daiyan"] = "怠宴",
  [":joy__daiyan"] = "结束阶段，你可以令一名角色从牌堆中获得一张<font color='red'>♥</font>基本牌，然后若其不是上回合此技能选择的角色，你摸一张牌。",
  ["joy__fumian1"] = "摸牌阶段摸牌数+%arg",
  ["joy__fumian2"] = "使用红色牌目标数+%arg",
  ["@joy__fumian1-turn"] = "福绵 摸牌数+",
  ["@joy__fumian2-turn"] = "福绵 目标数+",
  ["#joy__fumian-choose"] = "福绵：你可以为%arg额外指定%arg2个目标",
  ["#joy__daiyan-choose"] = "怠宴：你可以令一名角色摸一张<font color='red'>♥</font>基本牌，若其不为上回合选择的角色，你摸一张牌",
  ["@@joy__daiyan-tmp"] = "上次怠宴目标",

}

local huaman = General(extension, "joy__huaman", "shu", 4, 4, General.Female)
local mansi = fk.CreateViewAsSkill{
  name = "joy__mansi",
  anim_type = "offensive",
  prompt = "#mansi",
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local card = Fk:cloneCard("savage_assault")
    card:addSubcards(Self:getCardIds(Player.Hand))
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
}
local mansi_trigger = fk.CreateTriggerSkill{
  name = "#joy__mansi_trigger",
  events = {fk.Damaged},
  mute = true,
  main_skill = mansi,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill("joy__mansi") and data.card and data.card.trueName == "savage_assault"
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:drawCards(1, "@joy__mansi")
    player:broadcastSkillInvoke("joy__mansi")
    room:notifySkillInvoked(player, "joy__mansi", "drawcard")
    room:addPlayerMark(player, "@joy__mansi", 1)
    room.logic:trigger("fk.joy_mansi", player, { num = player:getMark("@joy_mansi")})
  end,
}
local souying = fk.CreateTriggerSkill{
  name = "joy__souying",
  mute = true,
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and not player:isNude() and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0 and
    (data.card.type == Card.TypeBasic or data.card:isCommonTrick()) and #AimGroup:getAllTargets(data.tos) == 1 then
      local room = player.room
      local events = {}
      if target == player then
        if data.to == player.id or room:getCardArea(data.card) ~= Card.Processing then return false end
        return true
      else
        if TargetGroup:getRealTargets(data.tos)[1] ~= player.id then return false end
        return true
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local prompt
    if target == player then
      prompt = "#souying1-invoke:::"..data.card:toLogString()
    else
      prompt = "#souying2-invoke:::"..data.card:toLogString()
    end
    local card = player.room:askForDiscard(player, 1, 1, true, self.name, true, ".", prompt, true)
    if #card > 0 then
      self.cost_data = card
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data, self.name, player, player)
    player:broadcastSkillInvoke(self.name)
    if target == player then
      room:notifySkillInvoked(player, self.name, "drawcard")
      if not player.dead and room:getCardArea(data.card) == Card.Processing then
        room:obtainCard(player, data.card, true, fk.ReasonJustMove)
      end
    else
      room:notifySkillInvoked(player, self.name, "defensive")
      table.insertIfNeed(data.nullifiedTargets, player.id)
    end
  end,
}
local zhanyuan = fk.CreateTriggerSkill{
  name = "joy__zhanyuan",
  anim_type = "special",
  events = {fk.EventPhaseStart,"fk.joy_mansi"},
  frequency = Skill.Wake,
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
        return target == player and player:hasSkill(self) and
      player.phase == Player.Start and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0
    else
        return target == player and player:hasSkill(self) and
      player.phase ~= Player.NotActive and
      player:usedSkillTimes(self.name, Player.HistoryGame) == 0
    end
  end,
  can_wake = function(self, event, target, player, data)
    return player:getMark("@joy__mansi") > 7
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets = table.map(room:getOtherPlayers(player), Util.IdMapper)
    if #targets == 0 then return end
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#joy__zhanyuan-choose", self.name, true)
    if #to > 0 then
      room:handleAddLoseSkills(player, "xili|-mansi", nil, true, false)
      room:handleAddLoseSkills(room:getPlayerById(to[1]), "xili", nil, true, false)
    end
  end,
}
mansi:addRelatedSkill(mansi_trigger)
huaman:addSkill("manyi")
huaman:addSkill(mansi)
huaman:addSkill(souying)
huaman:addSkill(zhanyuan)
huaman:addRelatedSkill("xili")
Fk:loadTranslationTable{
  ["joy__huaman"] = "花鬘",
  ["#joy__huaman"] = "芳踪载馨",
  ["joy__mansi"] = "蛮嗣",
  [":joy__mansi"] = "出牌阶段限一次，你可以将所有手牌当【南蛮入侵】使用；当一名角色受到【南蛮入侵】的伤害后，你摸一张牌。",
  ["joy__souying"] = "薮影",
  [":joy__souying"] = "每回合限一次，当你使用牌指定其他角色为唯一目标后，你可以弃置一张牌获得之；"..
  "当其他角色使用牌指定你为唯一目标后，你可以弃置一张牌令此牌对你无效。",
  ["joy__zhanyuan"] = "战缘",
  [":joy__zhanyuan"] = "觉醒技，准备阶段或你的回合内，若你已发动〖蛮嗣〗获得超过七张牌，你可以选择一名其他角色，"..
  "你与其获得技能〖系力〗，你失去技能〖蛮嗣〗。",
  ["@joy__mansi"] = "蛮嗣",
  ["#souying1-invoke"] = "薮影：你可以弃置一张牌，获得此%arg",
  ["#souying2-invoke"] = "薮影：你可以弃置一张牌，令此%arg对你无效",
  ["#joy__zhanyuan-choose"] = "战缘：你可以与一名其他角色获得技能〖系力〗",

}

local zhujianping = General(extension, "joy__zhujianping", "qun", 3)
zhujianping:addSkill("xiangmian")
zhujianping:addSkill("tianji")
Fk:loadTranslationTable{
  ["joy__zhujianping"] = "朱建平",
  ["#joy__zhujianping"] = "识面知秋",
}

local ruiji = General(extension, "joy__ruiji", "wu", 4, 4, General.Female)
ruiji:addSkill("wangyuan")
ruiji:addSkill("lingyin")
ruiji:addSkill("liying")
Fk:loadTranslationTable{
  ["joy__ruiji"] = "芮姬",
  ["#joy__ruiji"] = "柔荑弄钺",
  ["designer:joy__ruiji"] = "韩旭",
  ["illustrator:joy__ruiji"] = "匠人绘",
}


local yanrou = General(extension, "joy__yanrou", "wei", 4)
local xiangshu = fk.CreateTriggerSkill{
  name = "joy__xiangshu",
  anim_type = "support",
  frequency = Skill.Limited,
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish
    and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
    and #player.room.logic:getActualDamageEvents( 1, function(e) return e.data[1].from == player end) > 0
    and table.find(player.room.alive_players, function(p) return p:isWounded() end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local n = 0
    player.room.logic:getActualDamageEvents( 1, function(e)
      if e.data[1].from == player then
        n = n + e.data[1].damage
      end
    end,Player.HistoryGame)
    local targets = table.map(table.filter(room.alive_players, function(p) return p:isWounded() end), Util.IdMapper)
    if #targets == 0 then return end
    n = math.min(n, 5)
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#xiangshu-invoke:::"..n, self.name, true)
    if #to > 0 then
      self.cost_data = {to[1], n}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data[1])
    local n = self.cost_data[2]
    room:recover({
      who = to,
      num = math.min(n, to:getLostHp()),
      recoverBy = player,
      skillName = self.name
    })
    if to.dead then return end
    to:drawCards(n, self.name)
  end,
}
yanrou:addSkill("choutao")
yanrou:addSkill(xiangshu)
Fk:loadTranslationTable{
  ["joy__yanrou"] = "阎柔",
  ["#joy__yanrou"] = "冠玉啸北",
  ["illustrator:joy__yanrou"] = "凝聚永恒",
  ["joy__xiangshu"] = "襄戍",
  [":joy__xiangshu"] = "限定技，结束阶段，若你本回合造成过伤害，你可令一名已受伤角色回复X点体力并摸X张牌（X为你本局游戏造成的伤害值且最多为5）。",

}

local sunlingluan = General(extension, "joy__sunlingluan", "wu", 3, 3, General.Female)
sunlingluan:addSkill("lingyue")
sunlingluan:addSkill("pandi")
Fk:loadTranslationTable{
  ["joy__sunlingluan"] = "孙翎鸾",
  ["#joy__sunlingluan"] = "弦凤栖梧",
}

local yanbaihu = General(extension, "joy__yanbaihu", "qun", 4)
local zhidao = fk.CreateTriggerSkill{
  name = "joy__zhidao",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.Damage},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and data.to ~= player and
      not data.to.dead and not data.to:isAllNude() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:doIndicate(player.id, {data.to.id})
    local flag = {"h", "e", "j"}
    local areas = {Player.Hand, Player.Equip, Player.Judge}
    local cards = {}
    for i = 1, 3, 1 do
      if #data.to.player_cards[areas[i]] > 0 then
        table.insert(cards, room:askForCardChosen(player, data.to, flag[i], self.name))
      end
    end
    if #cards > 0 then
      room:obtainCard(player, cards, false, fk.ReasonPrey)
    end
    local mark = type(data.to:getMark("@@joy__zhidao-turn")) == "table" and data.to:getMark("@@joy__zhidao-turn") or {}
    table.insertIfNeed(mark,player.id)
    room:setPlayerMark(data.to,"@@joy__zhidao-turn",mark)
  end,
}
local zhidao_prohibit = fk.CreateProhibitSkill{
  name = "#joy__zhidao_prohibit",
  is_prohibited = function(self, from, to, card)
    return type(to:getMark("@@joy__zhidao-turn")) == "table" and table.contains(to:getMark("@@joy__zhidao-turn"),from.id)
  end,
}
local jili = fk.CreateTriggerSkill{
  name = "joy__bjili",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.TargetConfirming,fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if event == fk.CardUseFinished then
      return player:hasSkill(self) and data.card and data.damageDealt and data.extra_data and data.extra_data.joy__bjili and table.contains(data.extra_data.joy__bjili,player.id)
    else
      return player:hasSkill(self) and not target.dead and target:distanceTo(player) == 1 and
      data.card.color == Card.Red and (data.card.type == Card.TypeBasic or data.card:isCommonTrick()) and
      data.from ~= player.id and not table.contains(AimGroup:getAllTargets(data.tos), player.id) and
      U.canTransferTarget(player, data)
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.CardUseFinished then
      player:drawCards(1,self.name)
    else
      if data.card.is_damage_card or table.contains({"dismantlement", "snatch", "chasing_near"}, data.card.name) or data.card.is_derived then
        player:broadcastSkillInvoke(self.name, 1)
        room:notifySkillInvoked(player, self.name, "negative")
      else
        player:broadcastSkillInvoke(self.name, 2)
        room:notifySkillInvoked(player, self.name, "control")
      end
      room:doIndicate(player.id, {target.id})
      local targets = {player.id}
      if type(data.subTargets) == "table" then
        table.insertTable(targets, data.subTargets)
      end
      AimGroup:addTargets(room, data, targets)
      data.extra_data = data.extra_data or {}
      data.extra_data.joy__bjili = data.extra_data.joy__bjili or {}
      table.insertIfNeed(data.extra_data.joy__bjili,player.id)
    end
  end,
}
zhidao:addRelatedSkill(zhidao_prohibit)
yanbaihu:addSkill(zhidao)
yanbaihu:addSkill(jili)
Fk:loadTranslationTable{
  ["joy__yanbaihu"] = "严白虎",
  ["#joy__yanbaihu"] = "豺牙落涧",
  ["joy__zhidao"] = "雉盗",
  ["@@joy__zhidao-turn"] = "雉盗",
  ["#joy__zhidao_prohibit"] = "雉盗",
  [":joy__zhidao"] = "锁定技，当你于出牌阶段内第一次对区域里有牌的其他角色造成伤害后，你获得其手牌、装备区和判定区里的各一张牌，"..
  "然后直到回合结束，你不能再对其使用牌。",
  ["joy__bjili"] = "寄篱",
  [":joy__bjili"] = "锁定技，当一名其他角色成为红色基本牌或红色普通锦囊牌的目标时，若其与你的距离为1且"..
  "你既不是此牌的使用者也不是目标，你也成为此牌的目标;然后此牌结算时，若此牌造成过伤害，你摸一张牌。",

}

local liubian = General(extension, "joy__liubian", "qun", 3)
local dushi = fk.CreateTriggerSkill{
  name = "joy__dushi",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events = {fk.AfterDying,fk.Death},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self, false, true)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:handleAddLoseSkills(player,"-"..self.name)
    local targets = table.map(table.filter(room:getAlivePlayers(), function(p)
      return not p:hasSkill(self) end), Util.IdMapper)
    if #targets == 0 then return end
    local to = room:askForChoosePlayers(player, targets, 1, 1, "#joy__dushi-choose", self.name, false)
    if #to > 0 then
      to = to[1]
    else
      to = table.random(targets)
    end
    room:handleAddLoseSkills(room:getPlayerById(to), self.name, nil, true, false)
  end,

  refresh_events = {fk.EnterDying},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_refresh = function(self, event, target, player, data)
    player:broadcastSkillInvoke(self.name)
    player.room:notifySkillInvoked(player, self.name)
  end,
}
local dushi_prohibit = fk.CreateProhibitSkill{
  name = "#joy__dushi_prohibit",
  prohibit_use = function(self, player, card)
    if card.name == "peach" and not player.dying then
      return table.find(Fk:currentRoom().alive_players, function(p) return p.dying and p:hasSkill("joy__dushi") and p ~= player end)
    end
  end,
}
dushi:addRelatedSkill(dushi_prohibit)
liubian:addSkill("shiyuan")
liubian:addSkill(dushi)
liubian:addSkill("yuwei")
Fk:loadTranslationTable{
  ["joy__liubian"] = "刘辩",
  ["#joy__liubian"] = "弘农怀王",
  ["joy__dushi"] = "毒逝",
  [":joy__dushi"] = "锁定技，你处于濒死状态时，其他角色不能对你使用【桃】。你脱离濒死状态或死亡时，你失去本技能，然后选择一名其他角色获得〖毒逝〗。",
  ["#joy__dushi-choose"] = "毒逝：令一名其他角色获得〖毒逝〗",
  
}

local fanchou = General(extension, "joy__fanchou", "qun", 4)
local xingluan = fk.CreateTriggerSkill{
  name = "joy__xingluan",
  anim_type = "drawcard",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and
    data.tos and #TargetGroup:getRealTargets(data.tos) == 1 and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = room:getCardsFromPileByRule(".|6",2,"drawPile")
    if #cards > 0 then
      local ids , _ = U.askforChooseCardsAndChoice(player,cards, {"OK"}, self.name, "选择一张牌获得",nil, 1, 1,cards)
      local card
      if #ids > 0 then
        card = ids
      else
        card = table.random(cards,1)
      end
      table.removeOne(cards,card[1])
      room:moveCards({
        ids = card,
        to = player.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonPrey,
        proposer = player.id,
        skillName = self.name,
      })
      if #cards > 0 then
        room:moveCards({
          ids = cards,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonJustMove,
          proposer = player.id,
          skillName = self.name,
        })
      end
    else
      player:drawCards(6, self.name)
    end
  end,
}
fanchou:addSkill(xingluan)
Fk:loadTranslationTable{
  ["joy__fanchou"] = "樊稠",
  ["#joy__fanchou"] = "庸生变难",
  ["joy__xingluan"] = "兴乱",
  [":joy__xingluan"] = "出牌阶段限一次，当你使用一张仅指定一名目标角色的牌结算结束后，你可以从牌堆中观看两张点数为6的牌并选择获得其中一张，剩余牌置入弃牌堆（若牌堆中没有点数为6的牌，改为摸六张牌）。",

}

local dingyuan = General(extension, "joy__dingyuan", "qun", 4)
local cixiao = fk.CreateTriggerSkill{
  name = "joy__cixiao",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local tos = room:askForChoosePlayers(player, table.map(player.room:getOtherPlayers(player), Util.IdMapper), 1, 1, "#joy__cixiao-choose", self.name, true)
    if #tos > 0 then
      self.cost_data = {tos[1]}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data[1])
    room:handleAddLoseSkills(to, "joy__panshi", nil, true, false)
    if not player.dead and not to.dead then
      local tar = {}
      for _, p in ipairs(room:getOtherPlayers(to)) do
        if to:inMyAttackRange(p) and not to:isProhibited(p, Fk:cloneCard("slash")) then
          table.insertIfNeed(tar,p.id)
        end
      end
      if #tar <= 0 then return end
      local tos,cards = room:askForChooseCardsAndPlayers(player,1,1,{to.id},1,1, ".|.|.|hand","你可以将一张牌交给本次选择的“义子”，然后令其视为对一名其攻击范围内的角色使用一张【杀】。",self.name,true)
      if #cards > 0 then
        local ta = room:askForChoosePlayers(player,tar,1,1,"选择一名角色，视为 "..Fk:translate(to.general).." 对其使用一张【杀】。",self.name,true,true)
        if #ta > 0 then
          room:obtainCard(to, cards[1], false, fk.ReasonGive,player.id,self.name)
          local t = room:getPlayerById(ta[1])
          if to.dead or t.dead then return end
          if  not to:prohibitUse(Fk:cloneCard("slash")) and not to:isProhibited(t, Fk:cloneCard("slash"))then
            room:useVirtualCard("slash", nil,to,t, self.name, true)
          end
        end
      end
    end
  end,
}
local panshi = fk.CreateTriggerSkill{
  name = "joy__panshi",
  events = {fk.EventPhaseStart, fk.DamageCaused, fk.Damage},
  frequency = Skill.Compulsory,
  mute = true,
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and player == target then
      if event == fk.EventPhaseStart then
        return player.phase == Player.Start and table.find(player.room.alive_players, function (p)
          return p ~= player and p:hasSkill(cixiao.name, true) end)
      elseif event == fk.DamageCaused or event == fk.Damage then
        return player.phase == Player.Play and data.to:hasSkill(cixiao.name, true) and
        data.card and data.card.trueName =="slash" and not data.chain
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventPhaseStart then
      room:notifySkillInvoked(player, self.name, "negative")
      player:broadcastSkillInvoke(self.name)
      local fathers = table.filter(room.alive_players, function (p) return p ~= player and p:hasSkill(cixiao.name, true) end)
      if #fathers == 1 then
        room:doIndicate(player.id, {fathers[1].id})
        if player:isKongcheng() then return false end
        local card = room:askForCard(player, 1, 1, false, self.name, false, ".", "#panshi-give-to:"..fathers[1].id)
        if #card > 0 then
          room:obtainCard(fathers[1].id, card[1], false, fk.ReasonGive)
        end
      else
        local tos, id = room:askForChooseCardAndPlayers(player, table.map(fathers, Util.IdMapper), 1, 1, ".|.|.|hand", "#panshi-give", self.name, false)
        if #tos > 0 and id then
          room:obtainCard(tos[1], id, false, fk.ReasonGive)
        end
      end
    elseif event == fk.DamageCaused then
      room:notifySkillInvoked(player, self.name, "offensive")
      player:broadcastSkillInvoke(self.name)
      data.damage = data.damage + 1
    elseif event == fk.Damage then
      room:notifySkillInvoked(player, self.name, "negative")
      player:broadcastSkillInvoke(self.name)
      room:handleAddLoseSkills(player,"-"..self.name)
      player:endPlayPhase()
    end
  end,

  refresh_events = {fk.EventLoseSkill, fk.EventAcquireSkill},
  can_refresh = function(self, event, target, player, data)
    return player == target and data == self
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "@@joy__panshi_son", event == fk.EventAcquireSkill and 1 or 0)
  end,
}
dingyuan:addSkill(cixiao)
dingyuan:addSkill("xianshuai")
dingyuan:addRelatedSkill(panshi)
Fk:loadTranslationTable{
  ["joy__dingyuan"] = "丁原",
  ["#joy__dingyuan"] = "养虎为患",
  ["joy__cixiao"] = "慈孝",
  [":joy__cixiao"] = "准备阶段，，你可以令一名其他角色获得一个“义子”标记，然后你可交给其一张牌并令其视为对一名其攻击范围内的其他角色使用一张【杀】。拥有“义子”标记的角色获得技能〖叛弑〗。",
  ["joy__panshi"] = "叛弑",
  [":joy__panshi"] = "锁定技，准备阶段，你将一张手牌交给拥有技能〖慈孝〗的角色；你于出牌阶段使用的【杀】对其造成伤害时，此伤害+1且你于造成伤害后失去“义子”标记并结束出牌阶段。",
  ["#joy__cixiao-choose"] = "慈孝：你可选择一名其他角色，令其获得义子标记",
  ["@@joy__panshi_son"] = "义子",

}

local heqi = General(extension, "joy__heqi", "wu", 4)
local function QizhouChange(player, num, skill_name)
  local room = player.room
  local skills = player.tag["joy__qizhou"]
  if type(skills) ~= "table" then skills = {} end
  local suits = {}
  for _, e in ipairs(player.player_cards[Player.Equip]) do
    table.insertIfNeed(suits, Fk:getCardById(e).suit)
  end
  if #suits >= num then
    if not table.contains(skills, skill_name) then
      room:handleAddLoseSkills(player, skill_name, "joy__qizhou")
      table.insert(skills, skill_name)
    end
  else
    if table.contains(skills, skill_name) then
      room:handleAddLoseSkills(player, "-"..skill_name, "joy__qizhou")
      table.removeOne(skills, skill_name)
    end
  end
  player.tag["joy__qizhou"] = skills
end
local qizhou = fk.CreateTriggerSkill{
  name = "joy__qizhou",
  frequency = Skill.Compulsory,
  refresh_events = {fk.AfterCardsMove},
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill(self) then
      for _, move in ipairs(data) do
        if move.to == player.id and move.toArea == Card.PlayerEquip then
          return true
        end
        if move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip then
              return true
            end
          end
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    QizhouChange(player, 1, "ex__yingzi")
    QizhouChange(player, 2, "joy__qixi")
    QizhouChange(player, 3, "ty_ex__xuanfeng")
    QizhouChange(player, 4, "duanbing")
  end,
}
local qixi = fk.CreateTriggerSkill{
  name = "joy__qixi",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self.name) and target == player and player.phase == Player.Play
  end,
  on_cost = function(self, event, target, player, data)
    local targets = {}
    for _, p in ipairs(player.room.alive_players) do
      if #p:getCardIds("hej") > 0 then
        table.insert(targets,p.id)
      end
    end
    local to = player.room:askForChoosePlayers(player, targets, 1, 1, "#joy__qixi-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local to = player.room:getPlayerById(self.cost_data[1])
  if not player.dead and not to.dead then
    local card = player.room:askForCardChosen(player, to,"hej", self.name)
    player.room:throwCard(card,self.name,to,player)
  end
  end,
}
local duanbing = fk.CreateTriggerSkill{
  name = "joy__duanbing",
  anim_type = "offensive",
  events = {fk.AfterCardTargetDeclared},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash"
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local targets = {}
    for _, p in ipairs(room:getOtherPlayers(player)) do
      if not table.contains(TargetGroup:getRealTargets(data.tos), p.id) and player:distanceTo(p) == 1 and not player:isProhibited(p, data.card) then
        table.insertIfNeed(targets, p.id)
      end
    end
    if #targets > 0 then
      local tos = room:askForChoosePlayers(player, targets, 1, 1, "#joy__duanbing-choose", self.name, true)
      if #tos > 0 then
        self.cost_data = tos[1]
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    table.insert(data.tos, {self.cost_data})
  end,
}
local duanbing_effect = fk.CreateTriggerSkill{
  name = "#joy__duanbing_effect",
  mute = true,
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash"
    and player:distanceTo(player.room:getPlayerById(data.to)) == 1 and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    data.fixedResponseTimes = data.fixedResponseTimes or {}
    data.fixedResponseTimes["jink"] = 2
  end,
}
duanbing:addRelatedSkill(duanbing_effect)
Fk:addPoxiMethod{
  name = "joy__shanxi_show",
  card_filter = function(to_select, selected, data)
    local tempSlots = table.simpleClone(Self.equipSlots)
    local tempSealedSlots = table.simpleClone(Self.sealedSlots)
    for _, sealedSlot in ipairs(tempSealedSlots) do
      table.removeOne(tempSlots, sealedSlot)
    end
    local n = 1 + #tempSlots - #Self:getCardIds(Player.Equip)
    return #selected < n
  end,
  feasible = function(selected)
    return #selected > 0
  end,
}
local shanxi = fk.CreateActiveSkill{
  name = "joy__shanxi",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = function ()
    local tempSlots = table.simpleClone(Self.equipSlots)
    local tempSealedSlots = table.simpleClone(Self.sealedSlots)
    for _, sealedSlot in ipairs(tempSealedSlots) do
      table.removeOne(tempSlots, sealedSlot)
    end
    local n = 1 + #tempSlots - #Self:getCardIds(Player.Equip)
    return "#joy__shanxi-choose:::"..n
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    local target = Fk:currentRoom():getPlayerById(to_select)
    return #selected == 0 and not target:inMyAttackRange(Self) and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local to = room:getPlayerById(effect.tos[1])
    local card_data = {}
    local to_hands = {}
    for i = 1, to:getHandcardNum() do
      table.insert(to_hands, -1)
    end
    if #to_hands > 0 then
      table.insert(card_data, { to.general, to_hands })
    end
    if not player:isKongcheng() then
      table.insert(card_data, { player.general, player.player_cards[Player.Hand] })
    end
    if #card_data == 0 then return end
    local cards = room:askForPoxi(player, "joy__shanxi_show", card_data, nil, true)
    if #cards == 0 then return end
    local from_cards = table.filter(cards, function(id) return id ~= -1 end)
    local to_cards = (#from_cards == #cards) and {} or table.random(to:getCardIds("h"), #cards-#from_cards)
    player:showCards(from_cards)
    to:showCards(to_cards)
    cards = table.connect(from_cards, to_cards)
    local to_throw = table.filter(cards, function (id)
      return Fk:getCardById(id).name == "jink"
    end)
    if #to_throw > 0 then
      local moveInfos = {}
      local to_throw1 = table.filter(to_throw, function(id) return table.contains(from_cards, id)
      and not player:prohibitDiscard(Fk:getCardById(id)) end)
      if #to_throw1 > 0 then
        table.insert(moveInfos, {
          from = player.id,
          ids = to_throw1,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonDiscard,
          proposer = player.id,
          skillName = self.name,
        })
      end
      local to_throw2 = table.filter(to_throw, function(id) return table.contains(to_cards, id) end)
      if #to_throw2 > 0 then
        table.insert(moveInfos, {
          from = to.id,
          ids = to_throw2,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonDiscard,
          proposer = player.id,
          skillName = self.name,
        })
      end
      if #moveInfos > 0 then
        room:moveCards(table.unpack(moveInfos))
      end
      if player.dead or to.dead then return end
      card_data = {}
      if #to:getCardIds("e") > 0 then
        table.insert(card_data, { "$Equip", to:getCardIds("e") })
      end
      local nonshow = table.filter(to:getCardIds("h"), function(id) return not table.contains(to_cards, id) end)
      if #nonshow > 0 then
        to_hands = {}
        for i = 1, #nonshow do
          table.insert(to_hands, -1)
        end
        table.insert(card_data, { "$Hand", to_hands })
      end
      if #card_data == 0 then return end
      local card = room:askForCardChosen(player, to, { card_data = card_data }, self.name)
      if room:getCardArea(card) ~= Card.PlayerEquip then
        card = table.random(nonshow)
      end
      room:obtainCard(player, card, false, fk.ReasonPrey)
    end
  end,
}
heqi:addSkill(qizhou)
heqi:addSkill(shanxi)
heqi:addRelatedSkill("ex__yingzi")
heqi:addRelatedSkill(qixi)
heqi:addRelatedSkill("ty_ex__xuanfeng")
heqi:addRelatedSkill(duanbing)
Fk:loadTranslationTable{
  ["joy__heqi"] = "贺齐",
  ["#joy__heqi"] = "马踏群峦",
  ["joy__qizhou"] = "绮胄",
  [":joy__qizhou"] = "锁定技，你根据装备区里牌的花色数获得以下技能：1种以上-〖英姿〗；2种以上-〖奇袭〗；3种以上-〖旋风〗；4种-〖短兵〗。",
  ["joy__shanxi"] = "闪袭",
  [":joy__shanxi"] = "出牌阶段限一次，你可以展示你与一名攻击范围内不包含你的角色共计至多X张手牌（X为你的空置装备栏数 + 1），若其中有【闪】，弃置之，然后获得其一张未以此法展示的牌。",
  ["#joy__shanxi-choose"] = "闪袭：展示你与一名攻击范围内不包含你的角色共计至多 %arg 张手牌",
  ["joy__shanxi_show"] = "闪袭",
  ["joy__qixi"] = "奇袭",
  [":joy__qixi"] = "出牌阶段开始时，你可以选择一名角色弃置其区域内的一张牌。",
  ["#joy__qixi-choose"] = "奇袭：你可以弃置一名角色区域内的一张牌。",
  ["joy__duanbing"] = "短兵",
  [":joy__duanbing"] = "①你使用【杀】时可以多选择一名距离为1的角色为目标；②每回合限一次，你对距离为1的角色使用的【杀】需要两张【闪】才能抵消。",
  ["#joy__duanbing_effect"] = "短兵",
  ["#joy__duanbing-choose"] = "短兵：你可以额外选择一名距离为1的其他角色为目标",

}

local hujinding = General(extension, "joy__hujinding", "shu", 3, 6, General.Female)
local wuyuan = fk.CreateActiveSkill{
  name = "joy__wuyuan",
  anim_type = "support",
  card_num = 1,
  target_num = 1,
  prompt = "#joy__wuyuan",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and not player:isKongcheng()
  end,
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).trueName == "slash"
  end,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local card = Fk:getCardById(effect.cards[1])
    room:moveCardTo(card, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, true, player.id)
    if not player.dead and player:isWounded() then
      room:recover({
        who = player,
        num = 1,
        recoverBy = player,
        skillName = self.name
      })
    end
    if not player.dead then
      player:drawCards(1, self.name)
    end
    if not target.dead then
      if card.color == Card.Red and target:isWounded() then
        room:recover({
          who = target,
          num = 1,
          recoverBy = player,
          skillName = self.name
        })
      elseif card.color == Card.Black then
        room:addPlayerMark(target,"@joy__wuyuan",1)
      end
      local n = card.name ~= "slash" and 2 or 1
      target:drawCards(n, self.name)
    end
  end,
}
local wuyuan_trigger = fk.CreateTriggerSkill{
  name = "#joy__wuyuan_trigger",
  refresh_events = {fk.TurnEnd},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark("@joy__wuyuan") > 0
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player,"@joy__wuyuan",0)
  end,
}
local wuyan_targetmod = fk.CreateTargetModSkill{
  name = "#joy__wuyuan_targetmod",
  residue_func = function(self, player, skill, scope)
    if skill.trueName == "slash_skill" and player:getMark("@joy__wuyuan") > 0 then
      return player:getMark("@joy__wuyuan")
    end
    return 0
  end,
}
wuyuan:addRelatedSkill(wuyan_targetmod)
wuyuan:addRelatedSkill(wuyuan_trigger)
hujinding:addSkill(wuyuan)
hujinding:addSkill("deshi")
hujinding:addSkill("huaizi")
Fk:loadTranslationTable{
  ["joy__hujinding"] = "胡金定",
  ["#joy__hujinding"] = "怀子求怜",
  ["@joy__wuyuan"] = "杀次数+",
  ["#joy__wuyuan_trigger"] = "武缘",
  ["#joy__wuyuan_targetmod"] = "武缘",
  ["joy__wuyuan"] = "武缘",
  [":joy__wuyuan"] = "出牌阶段限一次，你可以将一张【杀】交给一名其他角色，然后你回复1点体力并与其各摸一张牌；若此【杀】为：<br>①<font color='red'>红色</font>，其回复1点体力；<br>②黑色，其下回合出【杀】次数+1；"..
  "<br>③属性【杀】，其多摸一张牌。",
  ["#joy__wuyuan"] = "武缘：将一张【杀】交给一名角色，你回复1点体力并与其各摸一张牌",

}

local sunhanhua = General(extension, "joy__sunhanhua", "wu", 3, 3, General.Female)
local huiling = fk.CreateTriggerSkill{
  name = "joy__huiling",
  frequency = Skill.Compulsory,
  events = {fk.CardUsing,fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if event == fk.CardUsing then
      return target == player and player:hasSkill(self)
    elseif event == fk.AfterCardsMove then
      if player:hasSkill(self) then
        for _, move in ipairs(data) do
          if move.from == player.id and  move.moveReason == fk.ReasonDiscard then
              return true
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local red, black = 0, 0
    local color
    for _, id in ipairs(room.discard_pile) do
      color = Fk:getCardById(id).color
      if color == Card.Red then
        red = red+1
      elseif color == Card.Black then
        black = black+1
      end
    end
    if red > black then
      if  event == fk.CardUsing and data.card.color == Card.Black   then
        room:addPlayerMark(player, "joy__sunhanhua_ling", 1)
        room:setPlayerMark(player, "@joy__sunhanhua_ling", "<font color='red'>" .. tostring(player:getMark("joy__sunhanhua_ling")) .. "</font>")
      end
      if player:isWounded() then
        room:recover{
          who = player,
          num = 1,
          recoverBy = player,
          skillName = self.name,
        }
      end
    elseif black > red then
      if event == fk.CardUsing and data.card.color == Card.Red  then
        room:addPlayerMark(player, "joy__sunhanhua_ling", 1)
        room:setPlayerMark(player, "@joy__sunhanhua_ling", tostring(player:getMark("joy__sunhanhua_ling")))
      end
      local targets = table.map(table.filter(room:getOtherPlayers(player), function(p)
        return not p:isAllNude() end), Util.IdMapper)
      if #targets > 0 then
        local to = room:askForChoosePlayers(player, targets, 1, 1, "#huiling-choose", self.name)
        if #to > 0 then
          to = room:getPlayerById(to[1])
          local id = room:askForCardChosen(player, to, "hej", self.name)
          room:throwCard({id}, self.name, to, player)
        end
      end
    end
  end,

  refresh_events = {fk.AfterCardsMove, fk.AfterDrawPileShuffle, fk.EventAcquireSkill, fk.EventLoseSkill},
  can_refresh = function(self, event, target, player, data)
    if event == fk.AfterCardsMove then
      if not player:hasSkill(self, true) then return false end
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile then
          return true
        end
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.DiscardPile then
            return true
          end
        end
      end
    elseif event == fk.AfterDrawPileShuffle then
      return player:hasSkill(self, true)
    elseif event == fk.EventAcquireSkill or event == fk.EventLoseSkill then
      return player == target and data == self
    end
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.EventLoseSkill then
      room:setPlayerMark(player, "joy__sunhanhua_ling", 0)
      room:setPlayerMark(player, "@joy__sunhanhua_ling", 0)
    else
      local red, black = 0, 0
      local color
      for _, id in ipairs(room.discard_pile) do
        color = Fk:getCardById(id).color
        if color == Card.Red then
          red = red+1
        elseif color == Card.Black then
          black = black+1
        end
      end
      local x = player:getMark("joy__sunhanhua_ling")
      local huiling_info = ""
      if red > black then
        huiling_info = "<font color='red'>" .. tostring(x) .. "</font>"
      elseif red < black then
        huiling_info = tostring(x)
      else
        huiling_info = "<font color='grey'>" .. tostring(x) .. "</font>"
      end
      room:setPlayerMark(player, "@joy__sunhanhua_ling", huiling_info)
    end
  end,
}
local chongxu = fk.CreateActiveSkill{
  name = "joy__chongxu",
  anim_type = "special",
  frequency = Skill.Limited,
  card_num = 0,
  target_num = 0,
  prompt = function(self)
    local n = math.min(Self:getMark("joy__sunhanhua_ling"),#Fk:currentRoom().players)
    return "#joy__chongxu:::"..n
  end,
  can_use = function(self, player)
    return player:getMark("joy__sunhanhua_ling") > 3 and player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and
    player:hasSkill(huiling, true)
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local x = math.min(player:getMark("joy__sunhanhua_ling"),#room.players)
    room:handleAddLoseSkills(player, "-joy__huiling", nil, true, false)
    room:changeMaxHp(player, x)
    room:handleAddLoseSkills(player, "taji|qinghuang", nil, true, false)
  end
}
sunhanhua:addSkill(huiling)
sunhanhua:addSkill(chongxu)
sunhanhua:addRelatedSkill("taji")
sunhanhua:addRelatedSkill("qinghuang")
Fk:loadTranslationTable{
  ["joy__sunhanhua"] = "孙寒华",
  ["#joy__sunhanhua"] = "青丝慧剑",
  ["joy__huiling"] = "汇灵",
  [":joy__huiling"] = "锁定技，你使用牌时或你的牌被弃置时，若弃牌堆中的红色牌数量多于黑色牌，你回复1点体力；"..
  "黑色牌数量多于红色牌，你可以弃置一名其他角色区域内的一张牌；若为使用牌且牌数较少的颜色与你使用牌的颜色相同，你获得一个“灵”标记。",
  ["joy__chongxu"] = "冲虚",
  [":joy__chongxu"] = "限定技，出牌阶段，若“灵”的数量不小于4，你可以失去〖汇灵〗，增加等量的体力上限（增加量至多为房间人数），并获得〖踏寂〗和〖清荒〗。",
  ["@joy__sunhanhua_ling"] = "灵",
  ["#joy__chongxu"] = "冲虚：你可以失去〖汇灵〗，加%arg点体力上限，获得〖踏寂〗和〖清荒〗",

}

local guosi = General(extension, "joy__guosi", "qun", 4)
local tanbei = fk.CreateActiveSkill{
  name = "joy__tanbei",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id
  end,
  on_use = function(self, room, use)
    local player = room:getPlayerById(use.from)
    local target = room:getPlayerById(use.tos[1])
    local choices = {"joy__tanbei2"}
    if not target:isNude() then
      table.insert(choices, 1, "joy__tanbei1")
    end
    local choice = room:askForChoice(target, choices, self.name)
    local targetRecorded = type(player:getMark(choice.."-turn")) == "table" and player:getMark(choice.."-turn") or {}
    table.insertIfNeed(targetRecorded, target.id)
    room:setPlayerMark(player, choice.."-turn", targetRecorded)
    if choice == "joy__tanbei1" then
      local id = room:askForCardChosen(player,target,"hej",self.name,"选择"..Fk:translate(target.general).."区域内的一张牌获得之")
      room:obtainCard(player.id, id, false, fk.ReasonPrey)
    end
  end,
}
--[[
local tanbei_refresh = fk.CreateTriggerSkill{
  name = "#joy__tanbei_refresh",

  refresh_events = {fk.PreCardUse},
  can_refresh = function(self, event, target, player, data)
    if player == target then
      local mark = player:getTableMark( "joy__tanbei2-turn")
      return #mark > 0 and table.find(TargetGroup:getRealTargets(data.tos), function (pid)
        return table.contains(mark, pid)
      end)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    data.extraUse = true
  end,
}]]
local tanbei_prohibit = fk.CreateProhibitSkill{
  name = "#joy__tanbei_prohibit",
  is_prohibited = function(self, from, to, card)
    return table.contains(from:getTableMark( "joy__tanbei1-turn"), to.id)
  end,
}
local tanbei_targetmod = fk.CreateTargetModSkill{
  name = "#joy__tanbei_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    return to and table.contains(player:getTableMark( "joy__tanbei2-turn"), to.id)
  end,
  bypass_distances =  function(self, player, skill, card, to)
    return to and table.contains(player:getTableMark( "joy__tanbei2-turn"), to.id)
  end,
}
local sidao = fk.CreateTriggerSkill{
  name = "joy__sidao",
  anim_type = "offensive",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) and player.phase == Player.Play and not player:isKongcheng() and
      player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 then
      return self.joysidao_tos and #self.joysidao_tos > 0
    end
  end,
  on_cost = function(self, event, target, player, data)  --TODO: target filter
    local tars = {}
    for _, pid in pairs(self.joysidao_tos) do
      if #player.room:getPlayerById(pid):getCardIds("hej") > 0 then
        table.insertIfNeed(tars,pid)
      end
    end
    if #tars <= 0 then return end
    local tar = player.room:askForChoosePlayers(player,tars,1,1,"伺盗：你可以获得一名相同目标区域内的一张牌",self.name,true)
    if #tar > 0 then
      self.cost_data = tar[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local p = room:getPlayerById(self.cost_data)
    if #p:getCardIds("hej") > 0 then
      local id = room:askForCardChosen(player,p,"hej",self.name,"选择"..Fk:translate(p.general).."区域内的一张牌获得之")
      room:obtainCard(player.id, id, false, fk.ReasonPrey)
    end
  end,

  refresh_events = {fk.TargetSpecified},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play and data.firstTarget
  end,
  on_refresh = function(self, event, target, player, data)
    self.joysidao_tos = {}
    local mark = player:getMark("joy__sidao-phase")
    if mark ~= 0 and #mark > 0 and #AimGroup:getAllTargets(data.tos) > 0 then
      for _, id in ipairs(AimGroup:getAllTargets(data.tos)) do
        if table.contains(mark, id) then
          table.insert(self.joysidao_tos, id)
        end
      end
    end
    if #AimGroup:getAllTargets(data.tos) > 0 then
      mark = AimGroup:getAllTargets(data.tos)
      table.removeOne(mark, player.id)
    else
      mark = 0
    end
    player.room:setPlayerMark(player, "joy__sidao-phase", mark)
  end,
}
--tanbei:addRelatedSkill(tanbei_refresh)
tanbei:addRelatedSkill(tanbei_prohibit)
tanbei:addRelatedSkill(tanbei_targetmod)
guosi:addSkill(tanbei)
guosi:addSkill(sidao)
Fk:loadTranslationTable{
  ["joy__guosi"] = "郭汜",
  ["#joy__guosi"] = "党豺为虐",
  ["joy__tanbei"] = "贪狈",
  [":joy__tanbei"] = "出牌阶段限一次，你可以令一名其他角色选择一项：1.你获得其区域内的一张牌，此回合不能再对其使用牌；"..
  "2.令你此回合对其使用牌无距离和次数限制。",
  ["joy__sidao"] = "伺盗",
  [":joy__sidao"] = "出牌阶段限一次，当你对一名其他角色连续使用两张牌后，你可获得其区域内的一张牌。",
  ["joy__tanbei1"] = "其获得你区域内的一张牌，此回合不能再对你使用牌",
  ["joy__tanbei2"] = "其本回合对你使用牌无距离和次数限制",
}

local zerong = General(extension, "joy__zerong", "qun", 4)
zerong:addSkill("cansi")
zerong:addSkill("fozong")

Fk:loadTranslationTable{
  ["joy__zerong"] = "笮融",
  ["#joy__zerong"] = "刺血济饥",
}

local huangfusong = General(extension, "joy__huangfusong", "qun", 4)
local juxia = fk.CreateTriggerSkill{
  name = "joy__juxia",
  anim_type = "special",
  priority = 2.11,
  mute = true,
  frequency = Skill.Compulsory,
  events ={fk.PindianResultConfirmed},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.PindianResultConfirmed then
        if player == data.from then
          return data.fromCard.number == 1
        elseif player == data.to then
          return data.toCard.number == 1
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
      return true
  end,
  on_use = function(self, event, target, player, data)
    if event == fk.PindianResultConfirmed then
      player.room:notifySkillInvoked(player,self.name)
      player:broadcastSkillInvoke(self.name)
      data.winner = player
      local pd_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Pindian)
      if pd_event then
        local pdata = pd_event.data[1]
        if player == pdata.from then
          if pdata.fromCard.number == 1 then
            for _, p in ipairs(player.room.players) do
              if pdata.results[p.id] then
                pdata.results[p.id].winner = player
              end
            end
          end
        elseif pdata.results[player.id] then
          if pdata.results[player.id].toCard.number == 1 then
            pdata.results[player.id].winner = player
          end
        end
      end
      player.room:sendLog{
        type = "#joy__juxia",
        from = player.id,
        arg = self.name,
      }
    end
  end,
}
huangfusong:addSkill("ty__fenyue")
huangfusong:addSkill(juxia)
Fk:loadTranslationTable{
  ["joy__huangfusong"] = "皇甫嵩",
  ["#joy__huangfusong"] = "志定雪霜",
  ["joy__juxia"] = "居下",
  [":joy__juxia"] = "锁定技，你拼点时，若你拼点牌的点数为A,此次拼点胜利者改为你。",
  ["#joy__juxia"] = " 因〖%arg〗的效果，此次拼点胜利者改为 %from "
}


local dongwan = General(extension, "joy__dongwan", "qun", 3, 3, General.Female)
dongwan:addSkill("shengdu")
dongwan:addSkill("jieling")
Fk:loadTranslationTable{
  ["joy__dongwan"] = "董绾",
  ["#joy__dongwan"] = "蜜言如鸩",
}

local dengzhi = General(extension, "joy__dengzhi", "shu", 3)
local weimeng = fk.CreateActiveSkill{
  name = "joy__weimeng",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = function (self, selected, selected_cards)
    local n = Self:getMark("@@"..self.name) > 0 and 1 or 0
    return "#joy__weimeng:::"..(Self.hp + n)
  end,
  can_use = function(self, player)
    local n = Self:getMark("@@"..self.name) > 0 and 1 or 0
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and (player.hp + n) > 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local n = player:getMark("@@"..self.name) > 0 and 1 or 0
    local cards = room:askForCardsChosen(player, target, 1, player.hp + n, "h", self.name)
    room:setPlayerMark(player,"@@"..self.name,0)
    local n1 = 0
    for _, id in ipairs(cards) do
      n1 = n1 + Fk:getCardById(id).number
    end
    room:obtainCard(player, cards, false, fk.ReasonPrey)
    if player.dead or player:isNude() or target.dead then return end
    local cards2
    if #player:getCardIds("he") <= #cards then
      cards2 = player:getCardIds("he")
    else
      cards2 = room:askForCard(player, #cards, #cards, true, self.name, false, ".",
        "#joy__weimeng-give::"..target.id..":"..#cards..":"..n1)
      if #cards2 < #cards then
        cards2 = table.random(player:getCardIds("he"), #cards)
      end
    end
    local n2 = 0
    for _, id in ipairs(cards2) do
      n2 = n2 + Fk:getCardById(id).number
    end
    room:obtainCard(target, cards2, false, fk.ReasonGive, player.id)
    if n1 < n2 then
      if not player.dead then
        player:drawCards(1, self.name)
      end
    elseif n1 > n2 then
      if not (player.dead or target.dead or target:isAllNude()) then
        local id = room:askForCardChosen(player, target, "hej", self.name)
        room:throwCard({id}, self.name, target, player)
      end
    elseif n1 == n2 then
      room:setPlayerMark(player,"@@"..self.name,1)
    end
  end,
}
dengzhi:addSkill("jianliang")
dengzhi:addSkill(weimeng)
Fk:loadTranslationTable{
  ["joy__dengzhi"] = "邓芝",
  ["#joy__dengzhi"] = "绝境的外交家",
  ["joy__weimeng"] = "危盟",
  ["@@joy__weimeng"] = "危盟+1",
  [":joy__weimeng"] = "出牌阶段限一次，你可以获得一名其他角色至多X张手牌，然后交给其等量的牌（X为你的体力值）。"..
  "若你给出的牌点数之和：大于获得的牌，你摸一张牌；小于获得的牌，你弃置其区域内一张牌；等于获得的牌，你下次发动“危盟”时X改为你的体力值+1。",
  ["#joy__weimeng"] = "危盟：获得一名其他角色至多%arg张牌，交还等量牌，根据点数执行效果",
  ["#joy__weimeng-give"] = "危盟：交还 %dest %arg张牌，若点数大于%arg2则摸一张牌，若小于则弃置其一张牌,若等于则下次本技能X改为你的体力值+1。",
  
}

local chenlin = General(extension, "joy__chenlin", "wei", 3)
local songci = fk.CreateActiveSkill{
  name = "joy__songci",
  anim_type = "control",
  mute = true,
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    local mark = player:getTableMark(self.name)
    return table.find(Fk:currentRoom().alive_players, function(p) return not table.contains(mark, p.id) end)
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    local mark = Self:getTableMark( self.name)
    return #selected == 0 and not table.contains(mark, to_select)
  end,
  on_use = function(self, room, effect)
    local target = room:getPlayerById(effect.tos[1])
    local player = room:getPlayerById(effect.from)
    local mark = player:getTableMark( self.name)
    table.insert(mark, target.id)
    room:setPlayerMark(player, self.name, mark)
    if #target.player_cards[Player.Hand] <= target.hp then
      room:notifySkillInvoked(player, self.name, "support")
      player:broadcastSkillInvoke(self.name, 1)
      target:drawCards(2, self.name)
    else
      room:notifySkillInvoked(player, self.name, "control")
      player:broadcastSkillInvoke(self.name, 2)
      room:askForDiscard(target, 2, 2, true, self.name, false)
    end
  end,
}
local songci_trigger = fk.CreateTriggerSkill{
  name = "#joy__songci_trigger",
  mute = true,
  main_skill = songci,
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    local mark = player:getTableMark( "joy__songci")
    return target == player and player:hasSkill(self) and player.phase == Player.Discard
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player.room:notifySkillInvoked(player, "joy__songci", "drawcard")
    player:broadcastSkillInvoke("joy__songci", 3)
    player:drawCards(1, "joy__songci")
  end,
}
chenlin:addSkill("bifa")
songci:addRelatedSkill(songci_trigger)
chenlin:addSkill(songci)
Fk:loadTranslationTable{
  ["joy__chenlin"] = "陈琳",
  ["#joy__chenlin"] = "破竹之咒",
  ["illustrator:ty__chenlin"] = "Thinking", -- 破竹之咒 皮肤
  ["joy__songci"] = "颂词",
  [":joy__songci"] = "①出牌阶段，你可以选择一名角色（每名角色每局游戏限一次），若该角色的手牌数：不大于体力值，其摸两张牌；大于体力值，其弃置两张牌。②弃牌阶段结束时，你摸一张牌。",
  ["#joy__songci_trigger"] = "颂词",
}

local zhangwen = General(extension, "joy__zhangwen", "wu", 3)
local songshu = fk.CreateActiveSkill{
  name = "joy__songshu",
  anim_type = "drawcard",
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return #selected == 0 and to_select ~= Self.id and Self:canPindian(Fk:currentRoom():getPlayerById(to_select))
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local pindian = player:pindian({target}, self.name)
    if pindian.results[target.id].winner == player then
      player:setSkillUseHistory(self.name, 0, Player.HistoryPhase)
    elseif room:askForSkillInvoke(player,self.name,nil,"是否令你与 "..Fk:translate(target.general).." 各摸两张牌？") then
      if not player.dead then
        player:drawCards(2, self.name)
      end
      if not target.dead then
        target:drawCards(2, self.name)
      end
    end
  end,
}
local sibian = fk.CreateTriggerSkill{
  name = "joy__sibian",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = room:getNCards(4)
    room:moveCards({
      ids = cards,
      toArea = Card.Processing,
      moveReason = fk.ReasonJustMove,
      skillName = self.name,
      proposer = player.id,
    })
    local min, max = 13, 1
    for _, id in ipairs(cards) do
      if Fk:getCardById(id).number < min then
        min = Fk:getCardById(id).number
      end
      if Fk:getCardById(id).number > max then
        max = Fk:getCardById(id).number
      end
    end
    local get = {}
    for i = #cards, 1, -1 do
      if Fk:getCardById(cards[i]).number == min or Fk:getCardById(cards[i]).number == max then
        table.insert(get, cards[i])
        table.removeOne(cards, cards[i])
      end
    end
    room:delay(1000)
    room:obtainCard(player, get, false, fk.ReasonJustMove)
    if #cards > 0 then
      local n = #player.player_cards[Player.Hand]
      local m = #player.player_cards[Player.Hand]
      for _, p in ipairs(room:getOtherPlayers(player)) do
        if #p.player_cards[Player.Hand] < n then
          n = #p.player_cards[Player.Hand]
        end
        if #p.player_cards[Player.Hand] > m then
          m = #p.player_cards[Player.Hand]
        end
      end
      local targets = {}
      for _, p in ipairs(room:getAlivePlayers()) do
        if #p.player_cards[Player.Hand] == n or #p.player_cards[Player.Hand] == m then
          table.insert(targets, p.id)
        end
      end
      local to = room:askForChoosePlayers(player, targets, 1, 1, "#joy__sibian-choose", self.name, true)
      if #to > 0 then
        room:obtainCard(to[1], cards, false, fk.ReasonGive, player.id)
      else
        room:moveCards({
          ids = cards,
          fromArea = Card.Processing,
          toArea = Card.DiscardPile,
          moveReason = fk.ReasonJustMove,
          skillName = self.name,
        })
      end
    end
    return true
  end,
}
zhangwen:addSkill(songshu)
zhangwen:addSkill(sibian)
Fk:loadTranslationTable{
  ["joy__zhangwen"] = "张温",
  ["#joy__zhangwen"] = "冲天孤鹭",
  ["joy__songshu"] = "颂蜀",
  [":joy__songshu"] = "出牌阶段限一次，你可以与一名其他角色拼点：若你没赢，你可令你和该角色各摸两张牌；若你赢，视为本阶段此技能未发动过。",
  ["joy__sibian"] = "思辩",
  [":joy__sibian"] = "摸牌阶段，你可以放弃摸牌，改为亮出牌堆顶的4张牌，你获得其中所有点数最大和最小的牌，然后你可以将剩余的牌交给一名手牌数最少或最多的角色。",
  ["#joy__sibian-choose"] = "思辩：你可以将剩余的牌交给一名手牌数最少或最多的角色",

}

local wutugu = General(extension, "joy__wutugu", "qun", 15)
local ranshang = fk.CreateTriggerSkill{
  name = "joy__ranshang",
  anim_type = "negative",
  frequency = Skill.Compulsory,
  events = {fk.Damaged, fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.Damaged then
        return data.damageType == fk.FireDamage
      else
        return player.phase == Player.Finish and player:getMark("@wutugu_ran") > 0
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.Damaged then
      room:addPlayerMark(player, "@wutugu_ran", data.damage)
    else
      room:loseHp(player, player:getMark("@wutugu_ran"), self.name)
      if not player.dead and player:getMark("@wutugu_ran") >= 2 then
        room:changeMaxHp(player, -2)
        if not player.dead then
          player:drawCards(player:getMark("@wutugu_ran"), self.name)
        end
      end
    end
  end,
}
wutugu:addSkill(ranshang)
wutugu:addSkill("ty__hanyong")
Fk:loadTranslationTable{
  ["joy__wutugu"] = "兀突骨",
  ["#joy__wutugu"] = "霸体金刚",
  ["joy__ranshang"] = "燃殇",
  [":joy__ranshang"] = "锁定技，当你受到1点火焰伤害后，你获得1枚“燃”标记；结束阶段，你失去X点体力（X为“燃”标记数），"..
  "然后若“燃”标记的数量不小于2个，则你减2点体力上限并摸X张牌。",
}


local zhoubuyi = General(extension, "joy__zhoubuyi", "wei", 3)
zhoubuyi:addSkill("shijiz")
zhoubuyi:addSkill("silun")
Fk:loadTranslationTable{
  ["joy__zhoubuyi"] = "周不疑",
  ["#joy__zhoubuyi"] = "幼有异才",
}


local huangquan = General(extension, "joy__huangquan", "shu", 3)
huangquan:addSkill("quanjian")
huangquan:addSkill("tujue")
Fk:loadTranslationTable{
  ["joy__huangquan"] = "黄权",
  ["#joy__huangquan"] = "忠事三朝",
}

local zongyu = General(extension, "joy__zongyu", "shu", 3)
local chengshang = fk.CreateTriggerSkill{
  name = "joy__chengshang",
  anim_type = "drawcard",
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Play  and
      data.card.suit ~= Card.NoSuit and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  on_cost = function(self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil,
      "#joy__chengshang-invoke:::"..data.card:getSuitString()..":"..tostring(data.card.number))
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = room:getCardsFromPileByRule(".|"..tostring(data.card.number).."|"..data.card:getSuitString())
    if #cards > 0 then
      for _, cid in ipairs(cards) do
        room:setCardMark(Fk:getCardById(cid),"@@joy__chengshang-turn",1)
      end
      room:moveCards({
        ids = cards,
        to = player.id,
        toArea = Card.PlayerHand,
        moveReason = fk.ReasonJustMove,
        proposer = player.id,
        skillName = self.name,
      })
    else
      player:setSkillUseHistory(self.name, 0, Player.HistoryPhase)
    end
  end,
}

local chengshang_max = fk.CreateMaxCardsSkill{
  name = "#joy__chengshang_max",
  exclude_from = function(self, player, card)
    return card:getMark("@@joy__chengshang-turn") > 0
  end,
}
chengshang:addRelatedSkill(chengshang_max)
zongyu:addSkill("qiao")
zongyu:addSkill(chengshang)
Fk:loadTranslationTable{
  ["joy__zongyu"] = "宗预",
  ["#joy__zongyu"] = "九酝鸿胪",
  ["joy__chengshang"] = "承赏",
  ["#joy__chengshang_max"] = "承赏",
  [":joy__chengshang"] = "出牌阶段内限一次，你使用的牌结算后，你可以获得牌堆中所有与此牌花色点数均相同的牌，以此法获得的牌本回合不计入手牌上限。"..
  "若你没有因此获得牌，此技能视为未发动过。",
  ["#joy__chengshang-invoke"] = "承赏：你可以获得牌堆中所有的%arg%arg2牌，以此法获得的牌本回合不计入手牌上限",
  
}



local wangshuang = General(extension, "joy__wangshuang", "wei", 8)
local zhuilie = fk.CreateTriggerSkill{
  name = "joy__zhuilie",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card.trueName == "slash" and
      not player:inMyAttackRange(player.room:getPlayerById(data.to))
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:addCardUseHistory(data.card.trueName, -1)
    local judge = {
      who = player,
      reason = self.name,
      pattern = ".",
    }
    room:judge(judge)
    if judge.card.sub_type and (judge.card.sub_type == Card.SubtypeWeapon or
      judge.card.sub_type == Card.SubtypeOffensiveRide or judge.card.sub_type == Card.SubtypeDefensiveRide) then
      data.additionalDamage = (data.additionalDamage or 0) + room:getPlayerById(data.to).hp - 1
    elseif judge.card.type == Card.TypeTrick and room:getCardArea(judge.card.id) == Card.Processing then
      room:obtainCard(player,judge.card,true,fk.ReasonPrey,player.id,self.name)
    elseif judge.card.type == Card.TypeBasic then
      room:loseHp(player, 1, self.name)
    end
  end,
}
local zhuilie_targetmod = fk.CreateTargetModSkill{
  name = "#joy__zhuilie_targetmod",
  bypass_distances =  function(self, player, skill)
    return player:hasSkill(self) and skill.trueName == "slash_skill"
  end,
}
zhuilie:addRelatedSkill(zhuilie_targetmod)
wangshuang:addSkill(zhuilie)
Fk:loadTranslationTable{
  ["joy__wangshuang"] = "王双",
  ["#joy__wangshuang"] = "遏北的悍锋",
  ["joy__zhuilie"] = "追猎",
  [":joy__zhuilie"] = "锁定技，你使用【杀】无距离限制；当你使用【杀】指定你攻击范围外的一名角色为目标后，此【杀】不计入次数且你进行一次判定，若结果为："..
  "<br>1.武器牌或坐骑牌，此【杀】伤害基数值增加至该角色的体力值；<br>2.锦囊牌，你获得之；<br>3.基本牌，否则你失去1点体力。",

}

local caochun = General(extension, "joy__caochun", "wei", 4)
caochun:addSkill("ty__shanjia")
Fk:loadTranslationTable{
  ["joy__caochun"] = "曹纯",
  ["#joy__caochun"] = "虎豹骑首",
}


local yangyi = General(extension, "joy__yangyi", "shu", 3)
yangyi:addSkill("ty__juanxia")
yangyi:addSkill("ty__dingcuo")
Fk:loadTranslationTable{
  ["joy__yangyi"] = "杨仪",
  ["#joy__yangyi"] = "武侯长史",
}

local liuye = General(extension, "joy__liuye", "wei", 3)
local poyuan_catapult = {{"joy__catapult", Card.Diamond, 9}}
local poyuan = fk.CreateTriggerSkill{
  name = "joy__poyuan",
  anim_type = "control",
  events = {fk.GameStart, fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and (event == fk.GameStart or (event == fk.TurnStart and target == player)) then
      if table.find(player:getEquipments(Card.SubtypeOffensiveRide), function(id) return Fk:getCardById(id).name == "joy__catapult" end) then
        return table.find(player.room:getOtherPlayers(player), function(p) return not p:isNude() end)
      else
        local catapult = table.find(U.prepareDeriveCards(player.room, poyuan_catapult, "joy__poyuan_catapult"), function (id)
          return player.room:getCardArea(id) == Card.Void
        end)
        return catapult and U.canMoveCardIntoEquip(player, catapult)
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if table.find(player:getEquipments(Card.SubtypeOffensiveRide), function(id) return Fk:getCardById(id).name == "joy__catapult" end) then
      local targets = table.filter(room:getOtherPlayers(player), function(p) return not p:isNude() end)
      if #targets == 0 then return end
      local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#joy__poyuan-choose", self.name, true)
      if #tos > 0 then
        self.cost_data = tos[1]
        return true
      end
    else
      return room:askForSkillInvoke(player, self.name, nil, "#joy__poyuan-invoke")
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if table.find(player:getEquipments(Card.SubtypeOffensiveRide), function(id) return Fk:getCardById(id).name == "joy__catapult" end) then
      local to = room:getPlayerById(self.cost_data)
      local cards = room:askForCardsChosen(player, to, 1, 2, "he", self.name)
      room:throwCard(cards, self.name, to, player)
    else
      local catapult = table.find(U.prepareDeriveCards(room, poyuan_catapult, "joy__poyuan_catapult"), function (id)
        return player.room:getCardArea(id) == Card.Void
      end)
      if catapult then
        room:setCardMark(Fk:getCardById(catapult), MarkEnum.DestructOutMyEquip, 1)
        U.moveCardIntoEquip (room, player, catapult, self.name, true, player)
      end
    end
  end,
}
liuye:addSkill(poyuan)
liuye:addSkill("huace")
Fk:loadTranslationTable{
  ["joy__liuye"] = "刘晔",
  ["#joy__liuye"] = "佐世之才",
  ["joy__poyuan"] = "破垣",
  [":joy__poyuan"] = "游戏开始时或回合开始时，若你的装备区里没有【霹雳车】，你可以将【霹雳车】置于装备区；若有，你可以弃置一名其他角色至多两张牌。<br>"..
  "<font color='grey'>【霹雳车】<br>♦9 装备牌·坐骑<br /><b>坐骑技能</b>：锁定技，你计算与其他角色的距离-1。<br>你回合内使用基本牌的伤害和回复数值+1且无距离限制。"..
    "你回合外使用或打出基本牌时摸一张牌。离开装备区时销毁。",
  ["#joy__poyuan-invoke"] = "破垣：你可以装备【霹雳车】",
  ["#joy__poyuan-choose"] = "破垣：你可以弃置一名其他角色至多两张牌",
}

local wufan = General(extension, "joy__wufan", "wu", 4)
wufan:addSkill("tianyun")
wufan:addSkill("yuyan")
wufan:addRelatedSkill("ty__fenyin")

Fk:loadTranslationTable{
  ["joy__wufan"] = "吴范",
  ["#joy__wufan"] = "占星定卜",
}

local weiwenzhugezhi = General(extension, "joy__weiwenzhugezhi", "wu",4)
local fuhai = fk.CreateActiveSkill{
  name = "joy__wfuhai",
  anim_type = "control",
  card_num = 0,
  target_num = 0,
  prompt = "令所有角色同时展示一张手牌，然后你选择一个方向，摸此方向上严格递增或严格递减的牌数，至少摸两张。",
  can_use = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:doIndicate(player.id, table.map(room.alive_players, Util.IdMapper))
    local targets = table.filter(room.alive_players, function(p) return not p:isKongcheng() end)
    local extraData = {
      num = 1,
      min_num = 1,
      include_equip = false,
      pattern = ".",
      reason = self.name,
    }
    for _, p in ipairs(targets) do
      p.request_data = json.encode({"choose_cards_skill", "所有角色同时展示一张手牌，然后"..Pg(player).."选择一个方向，摸此方向上严格递增或严格递减的牌数，至少摸两张。", false, extraData})
    end
    room:notifyMoveFocus(room.alive_players, self.name)
    room:doBroadcastRequest("AskForUseActiveSkill", targets)
    for _, p in ipairs(targets) do
      local id
      if p.reply_ready then
        local replyCard = json.decode(p.client_reply).card
        id = json.decode(replyCard).subcards[1]
      else
        id = table.random(p:getCardIds("h"))
      end
      room:setPlayerMark(p, "joy__wfuhai-tmp", id)
    end

    local all_cards = {}
    for _, p in ipairs(targets) do
      if not p.dead then
        local id = p:getMark("joy__wfuhai-tmp")
        p:showCards({id})
        room:setPlayerMark(p, "@joy__wfuhai-tmp", Fk:getCardById(id).number)
        table.insertIfNeed(all_cards,id)
      end
    end
    if player.dead or #all_cards == 0 then return end
    local ch1 = "从上家开始顺时针连续"
    local ch2 = "从下家开始逆时针连续"
    local choice = room:askForChoice(player,{ch1,ch2},self.name,"选择一个方向，摸等同该放向上严格单调递增或严格单调递减的牌数，至少摸两张")
    if choice == nil then
      choice = table.random({ch1,ch2})
    end 
      local ps = player
      local nonumber = false
      local n = 0
      local num = 0
      local lianxu = "no"
      if player:getMark("joy__wfuhai-tmp") ~= 0 then
        num = player:getMark("@joy__wfuhai-tmp")
        n = 1
        if num == 0 then
          nonumber = true
        end
      end
      local i = 1
      while i < #room.alive_players and not nonumber do
        i = i + 1
        for _, p in ipairs(room.alive_players) do
          if (ch1 == choice and p:getNextAlive() == ps) or (ch2 == choice and ps:getNextAlive() == p ) then
            ps = p
          end
        end
            if ps:getMark("joy__wfuhai-tmp") ~= 0 then
              local m = ps:getMark("@joy__wfuhai-tmp") 
              if lianxu == "no" then
                if num > 0 then
                  if m > num then
                    num = m
                    lianxu = "up"
                  elseif n < num and n > 0 then
                    num = m
                    lianxu = "dowm"
                  else
                    break
                  end
                else
                  num = m
                end
              elseif lianxu == "up" then
                if m > num then
                  num = m
                else
                  break
                end
              elseif lianxu == "down" then
                if m < num and n > 0 then
                  num = m
                else
                  break
                end
              end
              n = n + 1
            end
      end
      n = math.max(n,2)
      for _, p in ipairs(room.players) do
        room:setPlayerMark(p, "@joy__wfuhai-tmp",0)
        room:setPlayerMark(p, "joy__wfuhai-tmp",0)
      end
      if not player.dead then
        player:drawCards(n,self.name)
      end
  end,
}

weiwenzhugezhi:addSkill(fuhai)
Fk:loadTranslationTable{
  ["joy__weiwenzhugezhi"] = "卫温诸葛直",
  ["joy__wfuhai"] = "浮海",
  [ "@joy__wfuhai-tmp"] = "浮海点数",
  [":joy__wfuhai"] = "出牌阶段限一次，你可令所有角色同时展示一张手牌，然后你选择顺时针或逆时针，摸X张牌（X为该方向上角色展示的点数严格递增或严格递减的牌数，且至少为2）。"
}


local wangjun = General(extension, "joy__wangjun", "qun", 4)
wangjun:addSkill("tongye")
wangjun:addSkill("changqu")
Fk:loadTranslationTable{
  ["joy__wangjun"] = "王濬",
  ["#joy__wangjun"] = "遏浪飞艨",
}

local peiyuanshao = General(extension, "joy__peiyuanshao", "qun", 4)
peiyuanshao:addSkill("moyu")
Fk:loadTranslationTable{
  ["joy__peiyuanshao"] = "裴元绍",
  ["#joy__peiyuanshao"] = "买椟还珠",
}

local dongxie = General(extension, "joy__dongxie", "qun", 4, 4, General.Female)
local jiaoxia = fk.CreateViewAsSkill{
  name = "joy_jiaoxia",
  anim_type = "offensive",
  pattern = "slash",
  prompt = "你可以将手牌当做【杀】使用，若造成伤害，结算时你可以使用原卡牌！",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:currentRoom():getCardArea(to_select) == Card.PlayerHand
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return nil end
    local c = Fk:cloneCard("slash")
    c.skillName = self.name
    c:addSubcard(cards[1])
    return c
  end,
  enabled_at_play = function(self, player)
    return player.phase == Player.Play
  end,
  enabled_at_response = function(self, player, response)
    return false
  end,
}
local jiaoxia_delay = fk.CreateTriggerSkill{
  name = "#joy_jiaoxia_delay",
  anim_type = "offensive",
  events = {fk.CardUseFinished, fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    if target ~= player or not player:hasSkill(self) then return false end
    if event == fk.TargetSpecified then
      return data.card.trueName == "slash" and player.phase == player.Play and
      not table.contains(player:getTableMark("joy_jiaoxia_target-phase"), data.to)
    elseif event == fk.CardUseFinished then
      if table.contains(data.card.skillNames, "joy_jiaoxia") and data.damageDealt then
        local card = Fk:getCardById(data.card:getEffectiveId())
        return player:canUse(card) and not player:prohibitUse(card) and player.room:getCardArea(card) == Card.Processing
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
      return true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.TargetSpecified then
      room:addTableMark(player, "joy_jiaoxia_target-phase", data.to)
    elseif event == fk.CardUseFinished then
      local ids = Card:getIdList(data.card)
      U.askForUseRealCard(room, player, ids, ".", self.name, "#joy_jiaoxia-use:::"..Fk:getCardById(ids[1]):toLogString(),
      { expand_pile = ids, bypass_times = false, extraUse = false })
    end
  end,

  refresh_events = {fk.PreCardUse},
  can_refresh = function(self, event, target, player, data)
    if player == target and data.card.trueName == "slash" and player.phase == Player.Play and player:hasSkill(self) then
      local mark = player:getTableMark("joy_jiaoxia_target-phase")
      return table.find(TargetGroup:getRealTargets(data.tos), function (pid)
        return not table.contains(mark, pid)
      end)
    end
  end,
  on_refresh = function(self, event, target, player, data)
    data.extraUse = true
  end,
}
local jiaoxia_targetmod = fk.CreateTargetModSkill{
  name = "#joy_jiaoxia_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    return player:hasSkill(jiaoxia) and card and card.trueName == "slash" and to and
    not table.contains(player:getTableMark("joy_jiaoxia_target-phase"), to.id)
  end,
  bypass_distances =  function(self, player, skill, card, to)
    return player:hasSkill(jiaoxia) and card and card.trueName == "slash" and to and
    not table.contains(player:getTableMark("joy_jiaoxia_target-phase"), to.id)
  end,
}
local humei = fk.CreateActiveSkill{
  name = "joy_humei",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = function(self)
    return "狐魅：令一名角色执行一项"
  end,
  interaction = function(self)
    local choices = {}
    for i = 1, 3, 1 do
      if Self:getMark("joy_humei"..i.."-turn") == 0 then
        table.insert(choices, "joy_humei"..i.."-turn")
      end
    end
    return UI.ComboBox { choices = choices }
  end,
  can_use = function(self, player)
    for i = 1, 3, 1 do
      if player:getMark("joy_humei"..i.."-turn") == 0 then
        return player:usedSkillTimes("joy_humei", Player.HistoryPhase) < player:getMark("@joy_humei-phase")
      end
    end
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    local target = Fk:currentRoom():getPlayerById(to_select)
    if #selected == 0  then
      if self.interaction.data == "joy_humei1-turn" then
        return true
      elseif self.interaction.data == "joy_humei2-turn" then
        return not target:isNude()
      elseif self.interaction.data == "joy_humei3-turn" then
        return target:isWounded()
      end
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:setPlayerMark(player, self.interaction.data, 1)
    if self.interaction.data == "joy_humei1-turn" then
      target:drawCards(1, self.name)
    elseif self.interaction.data == "joy_humei2-turn" then
      local card = room:askForCard(target, 1, 1, true, self.name, false, ".", "#joy_humei-give:"..player.id)
      room:obtainCard(player, card[1], false, fk.ReasonGive, target.id)
    elseif self.interaction.data == "joy_humei3-turn" then
      room:recover{
        who = target,
        num = 1,
        recoverBy = player,
        skillName = self.name
      }
    end
  end,
}
local humei_trigger = fk.CreateTriggerSkill{
  name = "#joy_humei_trigger",
  events = {fk.Damage},
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(humei) and player.phase == Player.Play and player:getMark("@joy_humei-phase") < 3
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room  = player.room
    room:notifySkillInvoked(player, humei.name, "special")
    player:broadcastSkillInvoke(humei.name)
    player.room:setPlayerMark(player, "@joy_humei-phase",math.min(player:getMark("@joy_humei-phase") + data.damage,3))
  end,
  refresh_events = {fk.EventAcquireSkill},
  can_refresh = function (self, event, target, player, data)
    return target == player and data == self and player.phase == Player.Play
  end,
  on_refresh = function (self, event, target, player, data)
    local n = 0
    player.room.logic:getActualDamageEvents(1, function(e)
      if e.data[1].from == player then
        n = n + e.data[1].damage
      end
    end,Player.HistoryPhase)
    player.room:setPlayerMark(player, "@joy_humei-phase",math.min(3,n))
  end,
}
jiaoxia:addRelatedSkill(jiaoxia_targetmod)
jiaoxia:addRelatedSkill(jiaoxia_delay)
humei:addRelatedSkill(humei_trigger)
dongxie:addSkill(jiaoxia)
dongxie:addSkill(humei)
Fk:loadTranslationTable{
  ["joy__dongxie"] = "董翓",
  ["#joy__dongxie"] = "暗夜豺狐",
  ["joy_jiaoxia"] = "狡黠",
  [":joy_jiaoxia"] = "出牌阶段，你可将手牌当做【杀】使用。若你以此法使用的【杀】造成了伤害，"..
  "此【杀】结算后你可以视为使用原卡牌（有次数限制）。出牌阶段，你对每名角色使用第一张【杀】无距离和次数限制。",
  ["joy_humei"] = "狐魅",
  [":joy_humei"] = "出牌阶段限X次（X为你本阶段造成伤害点数），你可以令一名角色执行一个本回合未选择过的选项："..
  "1.摸一张牌；2.交给你一张牌；3.回复1点体力。",

  ["#joy_jiaoxia_delay"] = "狡黠",
  ["#joy_jiaoxia-use"] = "狡黠：你可以使用【%arg】",
  ["#joy_humei_trigger"] = "狐魅",
  ["@joy_humei-phase"] = "狐魅",
  ["joy_humei1-turn"] = "摸一张牌",
  ["joy_humei2-turn"] = "交给你一张牌",
  ["joy_humei3-turn"] = "回复1点体力",
  ["#joy_humei-give"] = "狐魅：请交给 %src 一张牌",
}
return extension